package com.rr.learningdemo.rabbitmq.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rr.learningdemo.rabbitmq.dto.MessageWithLevel;
import com.rr.learningdemo.rabbitmq.thread.RedisListenerThreadWithLevel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author zhuangcanrun
 * @Date 2021/06/21/16:51
 * @description
 **/

@Component
public class RabbitMQListenerForList {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisListenerThreadWithLevel redisListenerThreadWithLevel;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "queueForListMessage", durable = "true"),
                    exchange = @Exchange(value = "exchangeForDistinct", type = ExchangeTypes.DIRECT, durable = "true"),
                    key = "queueForListMessage"
            )
    )
    private void onMessage(Message message, Channel channel) throws IOException {
        String newMsg = new String(message.getBody(), StandardCharsets.UTF_8);
        List<MessageWithLevel> messages = JSON.parseArray(newMsg, MessageWithLevel.class);
        ListOperations listOperations = redisTemplate.opsForList();
        Long size = listOperations.size("list");
        for (MessageWithLevel m : messages) {
            Long index;
            if ((index = listOperations.indexOf("list", m.getKey())) == null) {
//                listOperations.set("list", m.getLevel(), m.getKey());
                listOperations.leftPush("list", m.getKey());
                System.out.println("插入" + m.getKey());
            }else {
                System.out.println("key:" + m.getKey() + "已存在，下标：" + index);
            }
        }
    }
}
